package main

import (
	"context"
	"fmt"

	"github.com/sirupsen/logrus"

	"gitee.com/zfd81/dbrs/engine"
	"gitee.com/zfd81/dbrs/internal/token"

	pb "gitee.com/zfd81/dbrs/proto/dbrspb"
)

type Broker struct {
}

func (d *Broker) StreamRows(request *pb.StreamRowsRequest, stream pb.Broker_StreamRowsServer) error {
	query := request.Query
	token := request.Token
	fmt.Println(query)
	fmt.Println(token)

	fields := []*pb.Field{}

	fields = append(fields, &pb.Field{
		Name: "name",
		Type: pb.Type_VARCHAR,
	}, &pb.Field{
		Name: "age",
		Type: pb.Type_INT64,
	}, &pb.Field{
		Name: "pwd",
		Type: pb.Type_VARCHAR,
	}, &pb.Field{
		Name: "desc",
		Type: pb.Type_TEXT,
	})

	for i := 0; i < 10; i++ {
		rows := []*pb.Row{}
		for j := 0; j < 1000; j++ {
			cols := []string{}
			cols = append(cols, fmt.Sprintf("name_%d_%d", i, j))
			cols = append(cols, fmt.Sprintf("%d_%d", i, j))
			cols = append(cols, fmt.Sprintf("pwd_%d_%d", i, j))
			cols = append(cols, fmt.Sprintf("desc_%d_%d", i, j))
			rows = append(rows, &pb.Row{
				Columns: cols,
			})
		}
		err := stream.Send(&pb.StreamRowsResponse{
			Fields: fields,
			Rows:   rows,
		})
		if err != nil {
			return err
		}
		logrus.Info(i)
	}
	return nil
}

func (d *Broker) GetSchema(ctx context.Context, request *pb.GetSchemaRequest) (*pb.GetSchemaResponse, error) {
	schema := []*pb.Table{}
	for i := 0; i < 20; i++ {
		schema = append(schema, &pb.Table{
			Name:    fmt.Sprintf("name_%d", i),
			Type:    "BASE TABLE",
			Comment: fmt.Sprintf("数据表_%d", i),
			Version: fmt.Sprintf("version_%d", i),
		})
	}

	return &pb.GetSchemaResponse{
		TableDefinitions: schema,
	}, nil
}

func (d *Broker) GetTable(ctx context.Context, request *pb.GetTableRequest) (*pb.Table, error) {
	tbl := &pb.Table{
		Columns: []*pb.Column{},
	}

	for i := 0; i < 20; i++ {
		tbl.Columns = append(tbl.Columns, &pb.Column{
			Name:     fmt.Sprintf("name_%d", i),
			Type:     pb.Type_TEXT,
			Nullable: true,
			Comment:  fmt.Sprintf("数据列_%d", i),
		})
	}

	return tbl, nil
}

func (d *Broker) Test(ctx context.Context, request *pb.TestRequest) (*pb.TestResponse, error) {
	claims, err := token.Parse(request.Token, engine.Token_Secret)
	if err != nil {
		return nil, err
	}
	return &pb.TestResponse{Result: claims.User}, nil
}
